module.exports = function(RED) {
  "use strict";
  function panelLEDNode(config) {
    RED.nodes.createNode(this, config);
    var node = this;
    node.name = config.name;
    node.pin = config.pin;
    node.log("Pin: " + node.pin);
    node.set = config.set;
    node.level = config.level;
    node.enableLow = config.enableLow;

    // 初始化 GPIO 状态文件路径
    var gpioPath = `/sys/bus/platform/drivers/xgpio/${node.pin}/state`;

    // 设置初始值
    if (node.set === true) {
      try {
        const fs = require('fs');
        // 写入初始值
        fs.writeFileSync(gpioPath, Number(node.level) ? '1' : '0');
        node.status({ fill: "green", shape: "dot", text: node.level.toString() });
      } catch (err) {
        node.error(err.message);
      }
    }

    this.on('input', function(msg) {
      try {
        const fs = require('fs');
        // 写入新的值
        fs.writeFileSync(gpioPath, Number(msg.payload) ? '1' : '0');
        node.status({ fill: "green", shape: "dot", text: msg.payload.toString() });
        if (RED.settings.verbose) {
          node.log("out: " + msg.payload);
        }
      } catch (err) {
        node.error(err.message);
      }
    });

    this.on('close', function() {
      // 清理操作（如果需要）
    });
  }
  RED.nodes.registerType("panel_led_out", panelLEDNode);
}